package vn.nad.aoeclips.screen.category.controller;

import java.util.ArrayList;

import vn.nad.android.aoeclips.R;
import vn.nad.aoeclips.common.model.entity.Category;
import vn.nad.aoeclips.common.utils.Constants;
import vn.nad.aoeclips.common.utils.Logger;
import vn.nad.aoeclips.common.view.AlertDialogManager;
import vn.nad.aoeclips.screen.category.controller.adapter.CategoryArrayAdapter;
import vn.nad.aoeclips.screen.category.controller.adapter.CategoryFragmentPagerAdapter;
import vn.nad.aoeclips.screen.category.controller.loader.DataCategoriesLoader;
import vn.nad.aoeclips.screen.setting.controller.SettingActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MainActivity extends FragmentActivity implements Constants,
		LoaderCallbacks<ArrayList<Category>>, OnItemClickListener,
		OnPageChangeListener {
	private String TAG = MainActivity.class.getSimpleName();

	private DrawerLayout mDrawerLayout;
	private ListView mListCategory;
	private ActionBarDrawerToggle mDrawerToggle;
	private ArrayList<Category> simpleCategories = new ArrayList<Category>();

	private ProgressDialog mProgressDialog;

	// Navigation drawer title
	private CharSequence mTitleCategory;
	private CharSequence mTitle;

	// adapter Category
	private CategoryArrayAdapter mAdapterCategory;

	private ViewPager mViewPager;

	private CategoryFragmentPagerAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mTitle = mTitleCategory = getTitle();
		initData();

	}

	// findViewById
	public void findViewById() {
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
		mListCategory = (ListView) findViewById(R.id.list_slidermenu);
		mViewPager = (ViewPager) findViewById(R.id.mViewPager);
		mAdapterCategory = new CategoryArrayAdapter(MainActivity.this,
				simpleCategories);
		mListCategory.setAdapter(mAdapterCategory);
	}

	private void initView() {
		Bundle bundle = new Bundle();
		bundle.putParcelableArrayList(
				CategoryFragmentPagerAdapter.ARGUMENT_CATEGORIES,
				simpleCategories);
		mAdapter = new CategoryFragmentPagerAdapter(
				getSupportFragmentManager(), bundle);

		mViewPager.setAdapter(mAdapter);
		mViewPager.setOffscreenPageLimit(0);
		mViewPager.setOnPageChangeListener(this);
	}

	// listener
	public void listener() {
		mListCategory.setOnItemClickListener(this);
	}

	public void initData() {
		initmProgressDialog();
		if (simpleCategories.size() == 0) {
			LoaderManager lm = getSupportLoaderManager();
			lm.destroyLoader(LOADER_ID_CATEGORIES);
			lm.initLoader(LOADER_ID_CATEGORIES, null, this);
		} else {
			findViewById();
			initView();
			listener();
			setActionBar();

		}
	}

	public void setActionBar() {
		// Enabling action bar app icon and behaving it as toggle button
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setIcon(
				new ColorDrawable(getResources().getColor(
						android.R.color.transparent)));

		mDrawerToggle = new ActionBarDrawerToggle(MainActivity.this,
				mDrawerLayout, R.drawable.ic_drawer, R.string.select_category,
				R.string.select_category) {
			public void onDrawerClosed(android.view.View drawerView) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu();

			};

			public void onDrawerOpened(android.view.View drawerView) {
				getActionBar().setTitle(mTitleCategory);
				invalidateOptionsMenu();
			};
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	private void initmProgressDialog() {
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setTitle(R.string.app_name);
		mProgressDialog.setMessage("Please wait...");
		mProgressDialog.setCancelable(false);
		mProgressDialog.setIndeterminate(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * On menu item selected
	 * */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// toggle nav drawer on selecting action bar app icon/title
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Handle action bar actions click
		switch (item.getItemId()) {
		case R.id.action_settings:
			// Selected settings menu item
			// launch Settings activity
			Intent intent = new Intent(MainActivity.this, SettingActivity.class);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/* *
	 * Called when invalidateOptionsMenu() is triggered
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// if nav drawer is opened, hide the action items
		// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerLayout);
		// menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	/**
	 * loader
	 */
	@Override
	public Loader<ArrayList<Category>> onCreateLoader(int arg0, Bundle bundle) {
		mProgressDialog.show();
		return new DataCategoriesLoader(this);
	}

	@Override
	public void onLoadFinished(Loader<ArrayList<Category>> loader,
			ArrayList<Category> data) {
		mProgressDialog.dismiss();
		simpleCategories.clear();
		simpleCategories.addAll(data);
		Logger.out(TAG, "simpleCategories ; " + simpleCategories.size());
		// mAdapterCategory = new CategoryArrayAdapter(MainActivity.this,
		// simpleCategories);

		findViewById();
		initView();
		listener();
		setActionBar();

	}

	@Override
	public void onLoaderReset(Loader<ArrayList<Category>> arg0) {

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		mViewPager.setCurrentItem(position);
		mDrawerLayout.closeDrawers();
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		// mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		// mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int position) {
		setTitle(simpleCategories.get(position).getCateName());
	}
	
	// on back press
	@Override
	public void onBackPressed() {
		AlertDialogManager.showAlert(MainActivity.this,
				getString(R.string.message_exit_apps),
				getString(R.string.dialog_yes),
				getString(R.string.dialog_cancel),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
	}
}
